package com.dd.cloud.user.service.agent.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.AgentConstants;
import com.dd.cloud.user.entity.agent.Agent;
import com.dd.cloud.user.entity.agent.AgentDoctorBind;
import com.dd.cloud.user.mapper.agent.AgentDoctorBindMapper;
import com.dd.cloud.user.service.agent.IAgentDoctorBindService;
import com.dd.cloud.user.service.agent.IAgentService;
import com.dd.cloud.common.exception.ZekeException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class AgentDoctorBindServiceImpl extends ServiceImpl<AgentDoctorBindMapper, AgentDoctorBind> implements IAgentDoctorBindService {
    @Autowired
    private IAgentService agentService;

    /**
     * 医生绑定代理商
     *
     * @param inviteCode
     * @param doctorId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Agent doctorBindAgent(String inviteCode, Integer doctorId) {
        QueryWrapper<Agent> qw = new QueryWrapper<>();
        qw.lambda().eq(Agent::getInviteCode, inviteCode);
        qw.lambda().ne(Agent::getStatus, AgentConstants.AgentStatus.DEL);
        Agent agent = agentService.getOne(qw);
        if (agent == null) {
            throw new ZekeException(400, "代理商邀请码不存在");
        }
        AgentDoctorBind agentDoctorBind = new AgentDoctorBind();
        agentDoctorBind.setDoctorId(doctorId);
        agentDoctorBind.setAgentId(agent.getId());
        agentDoctorBind.setStatus(AgentConstants.AgentDoctorBindStatus.NORMAL);
        agentDoctorBind.setCreateDate(LocalDateTime.now());
        save(agentDoctorBind);
        return agent;
    }
}
